package com.thinkit.cms.strategy.filter;
import com.thinkit.cms.dto.strategy.StrategyDto;
import com.thinkit.cms.service.job.impl.JobServiceImpl;
import com.thinkit.cms.strategy.checker.ActuatorCheck;
import com.thinkit.utils.utils.Checker;
import com.thinkit.utils.utils.SpringContextHolder;
import java.util.ArrayList;
import java.util.List;

/**
 * @author lg
 * 过滤器链条，可动态实现 执行器的组装拼合
 */
public class FilterChain extends ActuatorFilter {

    private List<Filter> filters = new ArrayList<Filter>();

    private List<ActuatorFilter> jobFilters = new ArrayList<ActuatorFilter>();

    private JobServiceImpl jobService = SpringContextHolder.getBean(JobServiceImpl.class);


    private int index=0;

    private int okCount=0;

    public int fcount() {
        return this.filters.size();
    }

    public FilterChain addFilter(Filter f) {
        if(Checker.BeNotNull(f)){
            filters.add(f);
        }
        return this;
    }


    public void addJobFilter(ActuatorFilter filter){
        jobFilters.add(filter);
    }

    public void setChecker(ActuatorCheck actuatorCheck) {
        if(Checker.BeNotNull(filters)){
            for(Filter filter:filters){
                filter.setChecker(actuatorCheck);
            }
        }
    }

    @Override
    public Filter setStrategy(StrategyDto strategy) {
        return this;
    }

    /**
     * 复用
     */
    public void reset() {
         this.index =0;
         this.okCount = 0;
    }

    /**
     * 标记成功次数
     */
    public void okFlag() {
        this.okCount +=1;
    }

    /**
     * 特效是否处理成功
     * @return
     */
    public boolean isOk() {
        return this.okCount >0;
    }

    @Override
    public void doFilter( Object params, FilterChain chain) {
        if(index==filters.size()){
            if(Checker.BeNotEmpty(jobFilters)){
                jobService.addJobs(jobFilters);
            }
            return ;
        }
        Filter f=filters.get(index);
        index++;
        f.doFilter( params, chain);
    }
}
